package com.selfdiscipline.data.local.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.MapInfo
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.selfdiscipline.data.local.entity.TimeRecordEntity
import kotlinx.coroutines.flow.Flow
import java.time.LocalDateTime

/**
 * 时间记录DAO接口，定义了对时间记录表的数据访问操作
 */
@Dao
interface TimeRecordDao {
    /**
     * 插入时间记录
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(timeRecord: TimeRecordEntity): Long
    
    /**
     * 更新时间记录
     */
    @Update
    suspend fun update(timeRecord: TimeRecordEntity)
    
    /**
     * 删除时间记录
     */
    @Delete
    suspend fun delete(timeRecord: TimeRecordEntity)
    
    /**
     * 通过ID删除时间记录
     */
    @Query("DELETE FROM time_records WHERE id = :id")
    suspend fun deleteById(id: Long)
    
    /**
     * 获取所有时间记录，按时间戳降序排序
     */
    @Query("SELECT * FROM time_records ORDER BY timestamp DESC")
    fun getAllTimeRecords(): Flow<List<TimeRecordEntity>>
    
    /**
     * 通过ID获取时间记录
     */
    @Query("SELECT * FROM time_records WHERE id = :id")
    fun getTimeRecordById(id: Long): Flow<TimeRecordEntity>
    
    /**
     * 按类别获取时间记录
     */
    @Query("SELECT * FROM time_records WHERE category = :category ORDER BY timestamp DESC")
    fun getTimeRecordsByCategory(category: String): Flow<List<TimeRecordEntity>>
    
    /**
     * 获取特定时间范围内的记录
     */
    @Query("SELECT * FROM time_records WHERE timestamp BETWEEN :startDate AND :endDate ORDER BY timestamp DESC")
    fun getTimeRecordsInRange(startDate: LocalDateTime, endDate: LocalDateTime): Flow<List<TimeRecordEntity>>
    
    /**
     * 获取总时长（分钟）
     */
    @Query("SELECT SUM(durationMinutes) FROM time_records")
    fun getTotalDurationMinutes(): Flow<Int>
    
    /**
     * 获取特定时间范围内的总时长（分钟）
     */
    @Query("SELECT SUM(durationMinutes) FROM time_records WHERE timestamp BETWEEN :startDate AND :endDate")
    fun getTotalDurationMinutesInRange(startDate: LocalDateTime, endDate: LocalDateTime): Flow<Int>
    
    /**
     * 获取类别分布（类别及其总时长）
     */
    @MapInfo(keyColumn = "category", valueColumn = "totalMinutes")
    @Query("SELECT category, SUM(durationMinutes) as totalMinutes FROM time_records GROUP BY category ORDER BY totalMinutes DESC")
    fun getCategoryDistribution(): Flow<Map<String, Int>>
} 